package com.xiaobai.zhuangxiuguanjia.activities;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaobai.zhuangxiuguanjia.R;
import com.xiaobai.zhuangxiuguanjia.Utils.OnLoginListener;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

public class LoginActivity extends AppCompatActivity
        implements View.OnClickListener, PlatformActionListener {

    private static final int MSG_SMSSDK_CALLBACK = 1;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;

    private Handler handler;
    private String smssdkAppkey;
    private String smssdkAppSecret;
    private OnLoginListener signupListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ShareSDK.initSDK(this);

//        SMSSDK.initSDK(this, "8356a9e83f45", "070a9af071d84adb6c50ad1d8a1c4a4b");
//        EventHandler eh = new EventHandler() {
//            public void afterEvent(int event, int result, Object data) {
//                Message msg = new Message();
//                msg.arg1 = event;
//                msg.arg2 = result;
//                msg.obj = data;
//                handler.sendMessage(msg);
//            }
//        };
//        //注册短信验证的监听
//        SMSSDK.registerEventHandler(eh);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("登陆");
        actionBar.setIcon(R.mipmap.abc_ic_ab_back_mtrl_am_darker);

        Button loginWeibo = (Button) findViewById(R.id.login_weibo);
        Button loginQQ = (Button) findViewById(R.id.login_qq);
        TextView createNewAccount = (TextView) findViewById(R.id.login_create_new_account);
        loginQQ.setOnClickListener(this);
        loginWeibo.setOnClickListener(this);
        createNewAccount.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_weibo:
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                authorize(sina);
                break;
            case R.id.login_qq:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                authorize(qq);
                break;
            case R.id.login_create_new_account:
                popupMsgLogin();
                break;
        }
    }

    private void popupMsgLogin() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("注册");
        View msgLoginView = LayoutInflater.from(this).inflate(R.layout.login_sms_layout, null);
        final Button aquireVerifyNum = (Button) msgLoginView.findViewById(R.id.aquire_verify_num);
        final Button createSubmit = (Button) msgLoginView.findViewById(R.id.create_submit);
        final EditText phoneNum = (EditText) msgLoginView.findViewById(R.id.phone_number);
        final EditText verifyNum = (EditText) msgLoginView.findViewById(R.id.verify_num);
        CheckBox read = (CheckBox) msgLoginView.findViewById(R.id.read_service_doc);
        TextView serviceDocLink = (TextView) msgLoginView.findViewById(R.id.service_doc_link);
        read.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    aquireVerifyNum.setEnabled(false);
                    createSubmit.setEnabled(false);
                } else {
                    aquireVerifyNum.setEnabled(true);
                    createSubmit.setEnabled(true);
                }
            }
        });
        serviceDocLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, ServiceDocActivity.class));
            }
        });

        aquireVerifyNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = phoneNum.getText().toString();
                if (TextUtils.isEmpty(number))
                    Toast.makeText(LoginActivity.this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                else if (!TextUtils.isEmpty(number) && number.length() < 11 && !number.startsWith("1"))
                    Toast.makeText(LoginActivity.this, "请输入正确的11位手机号", Toast.LENGTH_SHORT).show();
//                else
//                    SMSSDK.getVerificationCode("86", number);
            }
        });
        createSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = phoneNum.getText().toString();
                String verify = verifyNum.getText().toString();
                if (TextUtils.isEmpty(verify))
                    Toast.makeText(LoginActivity.this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
//                else
//                    SMSSDK.submitVerificationCode("86", number, verify);
            }
        });

        builder.setView(msgLoginView).show();
    }

    private void authorize(Platform plat) {
        if (plat == null) {
//            popupOthers();
            return;
        }

        plat.setPlatformActionListener(this);
        plat.SSOSetting(false);
        plat.showUser(null);
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//        if (i == Platform.ACTION_USER_INFOR) {
//            Message msg = new Message();
//            msg.what = MSG_AUTH_COMPLETE;
//            msg.obj = new Object[]{platform.getName(), hashMap};
//            handler.sendMessage(msg);
//        }

        //解析部分用户资料字段
        String id, name, description, profile_image_url;
        id = hashMap.get("id").toString();//ID
        name = hashMap.get("name").toString();//用户名
        description = hashMap.get("description").toString();//描述
        profile_image_url = hashMap.get("profile_image_url").toString();//头像链接
        String str = "ID: " + id + ";\n" +
                "用户名： " + name + ";\n" +
                "描述：" + description + ";\n" +
                "用户头像地址：" + profile_image_url;
        Log.d("res", "用户资料: " + str);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        if (i == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int i) {
//        if (i == Platform.ACTION_USER_INFOR) {
//            handler.sendEmptyMessage(MSG_AUTH_CANCEL);
//        }
    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
//            case MSG_AUTH_CANCEL:
//                Toast.makeText(this, "取消授权", Toast.LENGTH_SHORT).show();
//                break;
            case MSG_AUTH_ERROR:
                Toast.makeText(this, "授权出错", Toast.LENGTH_SHORT).show();
                break;
            case MSG_AUTH_COMPLETE:
                Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
                Object[] objs = (Object[]) msg.obj;
                String platform = (String) objs[0];
                HashMap<String, Object> res = (HashMap<String, Object>) objs[1];
                break;
            case MSG_SMSSDK_CALLBACK:
                break;
        }
        return false;
    }
}
